package org.ccahouse.ccatrain.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.ccahouse.ccacommons.common.GlobalException;
import org.ccahouse.ccacommons.common.MyHttpStatus;
import org.ccahouse.ccatrain.annotation.JwtIgnore;
import org.ccahouse.ccatrain.entity.Audience;
import org.ccahouse.ccatrain.util.JwtTokenUtil;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private Audience audience;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(JwtIgnore.class)) {
                JwtIgnore jwtIgnore = method.getAnnotation(JwtIgnore.class);
                if (jwtIgnore.required()) {
                    return true;
                }
            }
        }
        final String authHeader = request.getHeader(JwtTokenUtil.AUTH_HEADER_KEY);
        System.out.println("## authHeader= " + authHeader);
        if (StringUtils.isBlank(authHeader) || !authHeader.startsWith(JwtTokenUtil.TOKEN_PREFIX)) {
            System.out.println("##  用户未登录 ##");
            throw new GlobalException("token 验证失败", MyHttpStatus.HS_TOKEN_INSUFFICIENT.getCode());
        }
        final String token = authHeader.substring(7);
        if (audience == null) {
            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            audience = (Audience) factory.getBean("audience");
        }
        JwtTokenUtil.parseJwt(token, audience.getBase64Secret());
        JwtTokenUtil.getInstance().setUserId(JwtTokenUtil.getUserId(token, audience.getBase64Secret()));

        return true;
    }
}
